﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Free2AskWeb.Models;
using System.Web.Security;
using System.Web.Profile;
using Free2AskMVC4.Models;

namespace Free2AskWeb.Controllers
{
    public enum ManageMessageId
    {
        ChangePasswordSuccess,
        SetPasswordSuccess,
        RemoveLoginSuccess,
    }

    public class AccountController : Controller
    {
        //
        // GET: /Account/

        //[Authorize(Roles="admin")]
        //public ActionResult Index()
        //{
        //    Membership.GetAllUsers().
        //}

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ChangePassword(LocalPasswordModel model)
        {
            if (model.OldPassword == model.NewPassword)
            {
                ModelState.AddModelError("NewPassword","New password is the same as the old one.");
            }
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("Logon");
                }
                else
                {
                    ModelState.AddModelError("", "Wrong password.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model,string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("GetACLMemberInfo", "Account");
                    }
                }
            }
            else
            {
                ModelState.AddModelError("", "user name or psw is incorrect");
            }

            return View(model);
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        private bool isACLMember(string cardNumber)
        {
            Free2AskModel.Free2AskDBEntities db=new Free2AskModel.Free2AskDBEntities();

            var result = (from m in db.ACLMembers
                         where m.CardNo.Trim().ToUpper() == cardNumber.Trim().ToUpper()
                         select m).ToList();
            if (result == null || result.Count() == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private List<string> GetACLGroups(string cardNumber)
        {
            Free2AskModel.Free2AskDBEntities db = new Free2AskModel.Free2AskDBEntities();
            var groups = (from m in db.ACLMembers
                          where m.CardNo == cardNumber
                          select m.ACLGroup.Name).ToList();
            return groups;
        }

        [Authorize]
        public ActionResult GetACLMemberInfo()
        {
            MembershipUser user = Membership.GetUser();
            ProfileBase profile = ProfileBase.Create(user.UserName);
            object cardNumber = profile["CardNumber"];

            Free2AskModel.Free2AskDBEntities db = new Free2AskModel.Free2AskDBEntities();
            var aclMember = (from m in db.ACLMembers
                             where m.CardNo == (string)cardNumber
                             select m).FirstOrDefault();

            ACLMemberInfoModel info = new ACLMemberInfoModel();
            info.UserName = user.UserName;
            if (aclMember != null)
            {
                info.ACLGroups = GetACLGroups(cardNumber.ToString());
                info.CardNumber = cardNumber.ToString();
                info.RealName = aclMember.RealName;
            }
            return View(info);
        }

        [HttpPost]
        public ActionResult Register(RegisterModel regModel)
        {
            regModel.ConfirmPassword = regModel.Password;//This is only for testing purpose.
            if (ModelState.IsValid)
            {
                if (!isACLMember(regModel.CardNumber))
                {
                    ModelState.AddModelError("", "Unknown Card Number.");
                    return View(regModel);
                }
                MembershipCreateStatus createStatus;
                Membership.CreateUser(regModel.UserName, regModel.Password, regModel.EMail, "question", "answer", true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    ProfileBase profile = ProfileBase.Create(regModel.UserName);
                    profile["CardNumber"] = regModel.CardNumber;// "369";// regModel.CardNumber;
                    profile.Save();

                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", createStatus.ToString());
                }
            }

            return View(regModel);
        }

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        [Authorize]
        public ActionResult Settings()
        {
            return View();
        }

        [Authorize]
        public string Test()
        {
            Roles.CreateRole("admin");
            Roles.AddUserToRole(Membership.GetUser().UserName, "admin");
            return "done";
        }
    }
}
